//
//  MainViewController.m
//  OrangeNote
//
//  Created by 刘崇龙 on 16/1/19.
//  Copyright © 2016年 崇龙. All rights reserved.
//

#import "MainViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "SphereMenu.h"
#import "NotebookListTableViewCell.h"
#import "NotebookModel.h"
#import "NoteListTableViewController.h"
#import "UserTableViewController.h"
#import "LoginViewController.h"
#import "UserDataManager.h"
#import "UserModel.h"
#import "LocalDataManager.h"
#import "LoginViewController.h"


//#define kXXX  [UIScreen mainScreen].bounds.size.width/2
//#define kYYY  [UIScreen mainScreen].bounds.size.height-40

@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *noteBookArray;
@property(nonatomic,strong)NSString *noteTitle;
@end

NSString *mainViewControllerIdentifier = @"mainViewControllerIdentifier";

@implementation MainViewController

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    
#pragma mark --- LeanCloud测试
//    AVObject *post = [AVObject objectWithClassName:@"TestObject"];
//    [post setObject:@"Hello World!~~~~~~" forKey:@"words"];
//    [post saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//        if (succeeded) {
//            // 保存成功了！
//        }
//    }];
    

    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"我的" style:UIBarButtonItemStylePlain target:self action:@selector(toUserVC:)];
    
    self.navigationItem.titleView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"biaotilan"]];
    
    
#pragma mark --- 判断登陆
    
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser) {
        NSLog(@"已登陆!");
    }else{
        NSLog(@"未登录,请登陆!");
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
    }
    
    
    
    
#pragma mark --- tableView
    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"NotebookListTableViewCell" bundle:nil] forCellReuseIdentifier:mainViewControllerIdentifier];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
#pragma mark==================编辑导航栏右按钮=====为删除=====
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(showNoteTitle)];
    
    self.navigationController.navigationBar.translucent = NO;
    
    //刷新 UI 用
    self.noteBookArray = [[LocalDataManager sharedDataBase] selectAllNotebook];

    
    
    
    // 首页加号按钮, 还没设置具体动作哟哟哟切克闹蛮.
    UIImageView *buttonImg = [[UIImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2 - 30, [UIScreen mainScreen].bounds.size.height-130, 60, 60)];
    buttonImg.image = [UIImage imageNamed:@"iconfont-jikediancanicon09(3)"];
    [self.view addSubview:buttonImg];
    
    
    
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunched"]) {
        //这里判断是否是第一次
        _noteTitle = @"我的第一个笔记本";
        [self addNewNotebook];
    }
}


- (void)toUserVC:(UIBarButtonItem *)sender{
    UserTableViewController *userTableVC = [[UserTableViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:userTableVC];
    
    
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}


#pragma mark --- tableView方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _noteBookArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NotebookListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mainViewControllerIdentifier forIndexPath:indexPath];

    
     NotebookModel *notebook = self.noteBookArray[indexPath.row];
    NSMutableArray *countArr = [[LocalDataManager sharedDataBase] orderAllNoteByDescWithNotebookID:notebook.ID];
    
    cell.nameLabel.text = notebook.name;
    
    cell.countLabel.text = [NSString stringWithFormat:@"%ld",countArr.count];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NoteListTableViewController *noteListTVC = [[NoteListTableViewController alloc]init];
//        noteListTVC.navigationItem.titleView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"biaotilan"]];
    noteListTVC.notebookid = [_noteBookArray[indexPath.row] ID];
    
    [self.navigationController pushViewController:noteListTVC animated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}


#pragma mark ==========tebleView代理方法========================


//指定那些可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


//指定编辑风格
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        
        NotebookModel *book = _noteBookArray[indexPath.row];
        [_noteBookArray removeObjectAtIndex:indexPath.row];
        [[LocalDataManager sharedDataBase] deleteNotebookWithNotebookID:book.ID];
        
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView reloadData];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        
    }
}


#pragma mark==============添加 cell 的方法======================
//弹出添加新记事本标题 的输入框
-(void)showNoteTitle{
//    UserInputViewController *input = [UserInputViewController new];
//    [self.navigationController pushViewController:input animated:YES];
//    input.view.backgroundColor = [UIColor grayColor];
//    input.textField.delegate = self;
    
    UIViewController *VC = [[UIViewController alloc] init];
   
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:@"请输入笔记本名称"
                                                   delegate:nil
                                          cancelButtonTitle:@"取消"
                                        otherButtonTitles:@"完成", nil];
    VC.view.backgroundColor = [UIColor whiteColor];
    [VC.view addSubview:alert];
    
    // 基本输入框，显示实际输入的内容
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    alert.delegate = self;

    //设置输入框的键盘类型
    UITextField *tf = [alert textFieldAtIndex:0];
    tf.keyboardType = UIKeyboardTypeNamePhonePad;
    // 取得输入的值
//    NSString* text = tf.text;
//    NSLog(@"INPUT:%@", text);
    tf.delegate = self;
    [tf becomeFirstResponder];
    [alert show];
    
    [self presentViewController:VC animated:YES completion:nil];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        UITextField *tff = [alertView textFieldAtIndex:0];
        tff.delegate = self;
        NSLog(@"111");
        _noteTitle = tff.text;
        [self addNewNotebook];
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    }
    
    
}

//添加到数据库,和self.noteBookArray数组中
-(void)addNewNotebook{
    LocalDataManager *manager = [LocalDataManager sharedDataBase] ;
    NotebookModel *book = [[NotebookModel alloc] init];
    book.name = _noteTitle;
    NSLog(@"asdfadsfadsfafaf %@",_noteTitle);
    
    //添加到 数据库中
    [manager insertNotebookWithNotebook:book];
    //刷新数据(block 回调)
    manager.updateUI = ^(){
    
        [self.tableView reloadData];
       
    };
    
}


//textField 的代理方法检测到键盘回收,添加 note title
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    
    
    _noteTitle = textField.text;
    NSLog(@",huishoujianpan");
    //添加到数据库
  
    
    
    
    return YES;
}



#pragma mark=============懒加载self.noteBookArray===============
-(NSMutableArray *)noteBookArray{
    
    if (!_noteBookArray) {
        _noteBookArray = [[NSMutableArray alloc] init];
        
    }
    return _noteBookArray;
}


@end
